﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}
<h3>采购退货单修改</h3>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Demo</title>
	<!-- 请勿在项目正式环境中引用该 layui.css 地址 -->
	<link href="//unpkg.com/layui@2.10.3/dist/css/layui.css" rel="stylesheet">
	<style>
		body {
			background-color: #f2f2f2;
			padding: 20px;
		}

		.invoice-container {
			background-color: #fff;
			padding: 20px;
			border-radius: 5px;
			box-shadow: 0 0 10px rgba(0,0,0,0.1);
		}

		.form-title {
			margin-bottom: 20px;
			padding-bottom: 10px;
			border-bottom: 1px solid #eee;
			color: #333;
		}

		.form-table {
			width: 100%;
			margin-bottom: 15px;
		}

			.form-table td {
				padding: 10px 15px;
				vertical-align: top;
			}

		.form-actions {
			text-align: center;
			margin-top: 20px;
			padding-top: 20px;
			border-top: 1px solid #eee;
		}

		.layui-form-label {
			width: 100px;
		}

		.layui-input-block {
			margin-left: 130px;
		}

		.layui-form-item {
			margin-bottom: 15px;
		}

		.required:before {
			content: '*';
			color: red;
			margin-right: 4px;
		}

		/* 对话框样式 */
		.dialog-body {
			padding: 15px;
			overflow-y: auto;
			max-height: 70vh;
		}
		/* -------------------------- */
		.material-info-section {
			margin: 20px 0;
			border: 1px solid #ddd;
			padding: 15px;
			border-radius: 5px;
		}

		.section-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 15px;
		}

		.material-table {
			width: 100%;
			border-collapse: collapse;
		}

			.material-table th, .material-table td {
				border: 1px solid #ddd;
				padding: 8px;
				text-align: center;
			}

			.material-table th {
				background-color: #f2f2f2;
			}

			.material-table input {
				width: 100%;
				box-sizing: border-box;
				padding: 5px;
			}

		.btn {
			padding: 5px 10px;
			cursor: pointer;
			border: none;
			border-radius: 3px;
		}

		.btn-primary {
			background-color: #4CAF50;
			color: white;
		}

		.btn-save {
			background-color: #2196F3;
			color: white;
			padding: 8px 15px;
		}

		.btn-delete {
			background-color: #f44336;
			color: white;
		}

		.modal {
			display: none;
			position: fixed;
			z-index: 1;
			left: 0;
			top: 0;
			width: 100%;
			height: 100%;
			overflow: auto;
			background-color: rgba(0,0,0,0.4);
		}

		.modal-content {
			background-color: #fefefe;
			margin: 5% auto;
			padding: 20px;
			border: 1px solid #888;
			width: 80%;
			max-width: 900px;
		}

		.modal-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding-bottom: 10px;
			border-bottom: 1px solid #ddd;
		}

		.close {
			color: #aaa;
			font-size: 28px;
			font-weight: bold;
			cursor: pointer;
		}

		.search-bar {
			margin: 15px 0;
			display: flex;
		}

			.search-bar input {
				flex: 1;
				padding: 8px;
				margin-right: 10px;
			}

		.material-select-table {
			width: 100%;
			border-collapse: collapse;
		}

			.material-select-table th, .material-select-table td {
				border: 1px solid #ddd;
				padding: 8px;
				text-align: center;
			}

		.pagination {
			margin-top: 15px;
			text-align: right;
		}

			.pagination input {
				width: 50px;
				text-align: center;
				margin: 0 5px;
			}
	</style>
</head>
<body>
	<form class="layui-form" id="purchaseInvoiceForm" lay-filter="editForm">
		<input type="hidden" name="preturnorderid">
		<input type="hidden" name="returnsNum">
		<input type="hidden" name="outinNum">
		<input type="hidden" name="catchNum">
		<input type="hidden" name="copynumber">
		<table>
			<tr>
				<td>
					<div class="layui-form-item">
						<label class="layui-form-label required">单据编码：</label>
						<div class="layui-input-block">
							<input readonly type="text" name="documentCode" placeholder="请输入单据编码" autocomplete="off" class="layui-input">
						</div>
					</div>
				</td>
				<td>
					<div class="layui-form-item">
						<label class="layui-form-label required">业务类型：</label>
						<div class="layui-input-block">
							<select name="documentid" lay-verify="required">
								<option value="">请选择业务类型</option>
								<option value="1" selected>零部件</option>
								<option value="2">原材料</option>
								<option value="3">五金</option>
							</select>
						</div>
					</div>
				</td>
				<td>
					<div class="layui-form-item">
						<label class="layui-form-label required">采购单号：</label>
						<div class="layui-input-block">
							<input type="text" name="invoiceSettlementEntityId" placeholder="请输入采购单号" autocomplete="off" class="layui-input">
						</div>
					</div>
				</td>
				<td>
					<div class="layui-form-item">
						<label class="layui-form-label required">备注信息：</label>
						<div class="layui-input-block">
							<input type="text" name="notereason" placeholder="请输入备注信息" autocomplete="off" class="layui-input">
						</div>
					</div>
				</td>
			</tr>
			<tr>
				<td>
					<div class="layui-form-item">
						<label class="layui-form-label required">单据日期：</label>
						<div class="layui-input-block">
							<input type="text" name="documentTime" id="dialogInvoiceDate" autocomplete="off" class="layui-input" lay-verify="required">
						</div>
					</div>
				</td>
				<td>
					<div class="layui-form-item">
						<label class="layui-form-label required">操作员：</label>
						<div class="layui-input-block">
							<input readonly type="text" name="caozuoyuan" placeholder="请输入操作员" autocomplete="off" class="layui-input">
						</div>

					</div>
				</td>
				<td>
					<div class="layui-form-item">
						<label class="layui-form-label required">供应商：</label>
						<div class="layui-input-block">
							<input readonly type="text" name="supid" placeholder="请输入供应商" autocomplete="off" class="layui-input">
						</div>

					</div>
				</td>
			</tr>
			<tr>
				<td>
					<div class="layui-form-item">
						<label class="layui-form-label required">单据状态：</label>
						<div class="layui-input-block">
							<input readonly type="text" name="documentState" autocomplete="off" class="layui-input">
						</div>

					</div>
				</td>
				<td>
					<div class="layui-form-item">
						<label class="layui-form-label required">审核员：</label>
						<div class="layui-input-block">
							<input readonly type="text" name="shenheyuan" autocomplete="off" class="layui-input">
						</div>

					</div>
				</td>
				<td>
					<div class="layui-form-item">
						<label class="layui-form-label required">退货仓库：</label>
						<div class="layui-input-block">
							<select name="returnwarehouse" lay-verify="required">
								<option value="">请选择退货仓库</option>
								<option value="1" selected>成品仓</option>
								<option value="2">半成品仓</option>
								<option value="3">原料仓</option>
							</select>
						</div>
					</div>
				</td>
			</tr>
			<tr>
				<td>
					<div class="layui-form-item">
						<label class="layui-form-label required">业务状态：</label>
						<div class="layui-input-block">
							<select name="businessStuct" lay-verify="required">
								<option value="">请选择业务状态</option>
								<option value="1" selected>零部件发票</option>
								<option value="2">原材料发票</option>
								<option value="3">服务类发票</option>
							</select>
						</div>
					</div>
				</td>
				<td>
					<div class="layui-form-item">
						<label class="layui-form-label">审核日期：</label>
						<div class="layui-input-block">
							<input readonly type="text" name="shenheDate" id="dialogInvoiceDate" autocomplete="off" class="layui-input" lay-verify="required">
						</div>

					</div>
				</td>
				<td>
					<div class="layui-form-item">
						<label class="layui-form-label required">退货原因：</label>
						<div class="layui-input-block">
							<select name="reasonreturn" lay-verify="required">
								<option value="" selected>无</option>
								<option value="外观原因">外观原因</option>
								<option value="性能原因">性能原因</option>
							</select>
						</div>
					</div>
				</td>
			</tr>
			<tr>
				<button id="save-btn" class="layui-btn" lay-submit lay-filter="saveBtn">
					<i class="layui-icon">&#xe608;</i> 保存
				</button>
				<button type="button" class="layui-btn layui-btn-normal" id="dialogCancelBtn">
					<i class="layui-icon">&#x1006;</i> 取消
				</button>
				<button type="button" class="layui-btn layui-btn-primary" id="auditBtn">
					<i class="layui-icon">&#xe605;</i> 审核
				</button>
				<button type="button" class="layui-btn layui-btn-danger" id="antiAuditBtn">
					<i class="layui-icon">&#x1007;</i> 反审核
				</button>
				<button type="button" class="layui-btn layui-btn-default" id="collapseBtn">
					<i class="layui-icon">&#xe61a;</i> 收起
				</button>
			</tr>
		</table>
	</form>
	<!---------------------------------------->
	<div class="material-info-section">
		<div class="section-header">
			<h3>物料信息</h3>
			<button id="add-material-btn" class="btn btn-primary">引入</button>
		</div>

		<table class="material-table">
			<thead>
				<tr>
					<th width="10">序号</th>
					<th width="15">跟单编号</th>
					<th width="15">物料编码</th>
					<th width="15">物料名称</th>
					<th width="12%">型号规格</th>
					<th width="10">主计量</th>
					<th width="12">批号</th>
					<th width="8">数量</th>
					<th width="10">出库数量</th>
					<th width="40">退货说明</th>
					<th width="8">操作</th>
				</tr>
			</thead>
			<tbody id="material-tbody">
			</tbody>
		</table>
		<!-- 物料选择模态框 -->
		<div id="material-modal" class="modal">
			<div class="modal-content">
				<div class="modal-header">
					<h4>选择物料</h4>
					<span class="close">&times;</span>
				</div>
				<div class="modal-body">
					<div class="search-bar">
						<input type="text" id="material-search" placeholder="输入物料编码或名称搜索">
						<button id="search-btn">搜索</button>
					</div>
					<table class="material-select-table">
						<thead>
							<tr>
								<th>物料编码</th>
								<th>物料名称</th>
								<th>型号规格</th>
								<th>主计量</th>
								<th>操作</th>
							</tr>
						</thead>
						<tbody id="material-select-tbody">
							<!-- 物料选择数据会在这里 -->
						</tbody>
					</table>
					<div class="pagination">
						<span>共52条</span>
						<span>100条/页</span>
						<span>前往</span>
						<input type="number" value="1" min="1">
						<span>页</span>
					</div>
				</div>
			</div>
		</div>

	</div>
	<script src="//unpkg.com/layui@2.10.1/dist/layui.js"></script>

	<script>
		layui.use(['table', 'jquery', 'layer', 'form', 'laydate'],function(){
			var table = layui.table;
			var $ = layui.jquery;
			var layer = layui.layer;
			var form = layui.form;
			var laydate = layui.laydate;

			// 初始化日期范围
			laydate.render({
				elem: '#begindate'
			});

			laydate.render({
				elem: '#enddate'
			});

			laydate.render({
				elem: '#dialogInvoiceDate',
				format: 'yyyy-MM-dd',
			});

			// 从sessionStorage获取编辑数据
			var editDataStr = sessionStorage.getItem('editData');

			if(editDataStr) {
				console.log(editDataStr)
				var editData = JSON.parse(editDataStr);

				// 填充表单数据
				form.val('editForm', { // editForm是表单的lay-filter值
					"preturnorderid":editData.preturnorderid,
					"copynumber":editData.copynumber,
					"invoiceSettlementEntityId":editData.invoiceSettlementEntityId,
					"documentStuct":editData.documentStuct,
					"supid":editData.supid,
					"supplierName":editData.supplierName,
					"returnsNum":editData.returnsNum,
					"outinNum":editData.outinNum,
					"catchNum":editData.catchNum,
					"documentTime":editData.documentTime,
					"documentCode":editData.documentCode,
					"documentState":editData.documentState,
					"caozuoyuan":editData.caozuoyuan,
					"shenheyuan":editData.shenheyuan,
					"shenheDate":editData.shenheDate,
					"businessStuct":editData.businessStuct,
					"documentid":editData.documentid,
					"returnwarehouse":editData.returnwarehouse,
					"reasonreturn":editData.reasonreturn,
					"notereason":editData.notereason,
					"material_code":editData.material_code,
					//"material_name":editData.material_name
				});

				// 渲染表单
				form.render();
			}

			// 监听提交
			form.on('submit(saveBtn)', function(data){
				// 获取表单数据
				var formData = data.field;
				console.log("formData:",formData)
				$.ajax({
					//url: 'http://localhost:5090/api/PurchaseInvoices/UpdPurchaseArrival',
					url: "@ViewBag.BaseUrl/T8/PurchaseInvoices/UpdPurchaseArrival",
					type: 'POST',
					data: JSON.stringify(formData),
					contentType: 'application/json',
					success: function(res) {
						console.log("修改数据:",res)
						if(res.code==206) {
							layer.msg('修改成功', {icon: 1});
							// 返回列表页
							setTimeout(function(){
								window.location.href = 'PreturnorderList'; // 列表页A的路径
							}, 1000);
						} else {
							layer.msg(res.message || '修改失败', {icon: 2});
						}
					},
					error: function() {
						layer.msg('请求失败，请稍后再试', {icon: 2});
					}
				});

				return false; // 阻止表单跳转
			});


		})
	</script>
	<script>

		document.addEventListener('DOMContentLoaded', function(){
			let rowCount = 0;
			const modal = document.getElementById('material-modal');
			// 新增物料行
				//document.getElementById('add-material-btn').addEventListener('click', function() {
					rowCount++;
					const tbody = document.getElementById('material-tbody');
					const newRow = document.createElement('tr');
					newRow.dataset.index = rowCount;

					newRow.innerHTML = `
						<td>${rowCount}</td>
						<td><input type="text" class="order-number" value="手工单据"></td>
						<td>
							<div class="material-code-select">
								<input type="text" value="CGTH000001" class="material-code" placeholder="点击选择">
								<button class="btn-select">选择</button>
							</div>
						</td>
						<td><input type="text" class="receipt-number" value="手工单据"></td>

						<td><input type="text" class="material-name" value="测试C" readonly></td>
						<td><input type="text" class="specification" value="90*90" readonly></td>
						<td><input type="text" class="unit" value="只" readonly></td>
						<td><input type="number" class="pcount" min="0" step="1"></td>
						<td><input type="number" class="price" min="0" step="1"></td>
						<td><input type="text" class="shuoming" value="凄凄切切"></td>

						<td><button class="btn-delete">删除</button></td>
					`;

					// 为税率输入框绑定input事件
					const bindTaxLvInputEvent = function () {
						const taxLvInputs = document.querySelectorAll('.taxLv');
						taxLvInputs.forEach(function (taxLvInput) {
							const howmanyInput = taxLvInput.closest('tr').querySelector('.howmany');
							const taxAmountInput = taxLvInput.closest('tr').querySelector('.taxAmount');
							taxLvInput.addEventListener('input', function () {
								const amount = parseFloat(howmanyInput.value) || 0;
								const taxRate = parseFloat(taxLvInput.value) / 100 || 0;
								taxAmountInput.value = (amount * taxRate).toFixed(2);
							});
						});
					};
					bindTaxLvInputEvent();
					// 新增物料行时也需要重新绑定事件
					document.getElementById('add-material-btn').addEventListener('click', function () {
						// 已有代码逻辑...
						bindTaxLvInputEvent();
					});
					//pcount数量
					//price单价
					//howmany金额
					//taxLv税率
					//taxAmount税额
					tbody.appendChild(newRow);

						// 绑定数量和单价输入框的input事件
						const pcountInput = newRow.querySelector('.pcount');
						const priceInput = newRow.querySelector('.price');
						const howmanyInput = newRow.querySelector('.howmany');
							pcountInput.addEventListener('input', function () {
								const quantity = parseFloat(pcountInput.value) || 0;
								const unitPrice = parseFloat(priceInput.value) || 0;
								howmanyInput.value = (quantity * unitPrice).toFixed(2);
							});
								 priceInput.addEventListener('input', function () {
									const quantity = parseFloat(pcountInput.value) || 0;
									const unitPrice = parseFloat(priceInput.value) || 0;
									howmanyInput.value = (quantity * unitPrice).toFixed(2);
								});

					// 绑定选择按钮事件
					newRow.querySelector('.btn-select').addEventListener('click', function() {
						// 明确使用window对象
						window.currentSelectingRow = {
							index: rowCount,
							element: newRow
						};
						console.log("设置当前选中行:", window.currentSelectingRow);
						openMaterialModal();
					});

					// 绑定删除按钮事件
					newRow.querySelector('.btn-delete').addEventListener('click', function() {
						tbody.removeChild(newRow);
						// 重新排序序号
						updateRowNumbers();
					});
				//});

				// 打开物料选择模态框
				function openMaterialModal() {
					if (modal) {
						modal.style.display = 'block';
						loadMaterialData();
					} else {
						console.error('找不到模态框元素');
					}
				}

				// 关闭模态框
				 document.querySelector('.close')?.addEventListener('click', function() {
					if (modal) modal.style.display = 'none';
				});

				// 加载物料数据到选择表格
				function loadMaterialData(searchParams ={}) {
					const tbody = document.getElementById('material-select-tbody');
					tbody.innerHTML = '';

					// 构建查询参数
					const queryParams = new URLSearchParams();
					if (searchParams.material_code) queryParams.append('material_code', searchParams.material_code);
					if (searchParams.material_name) queryParams.append('material_name', searchParams.material_name);

					//---------------------------
					// 从服务器获取数据
					fetch(`@ViewBag.BaseUrl/T7/Materials/GetMaterial_Basic?${queryParams.toString()}`)
					.then(response => response.json())
					.then(data => {
						if (data.code === 0 && data.data) {
							// 清空表格
							//tbody.innerHTML = '';

							// 填充数据
							data.data.forEach(material => {
								const row = document.createElement('tr');
								row.innerHTML = `
									<td>${material.material_code}</td>
									<td>${material.material_name}</td>
									<td>${material.model_specification}</td>
									<td>${material.unit_of_measurement_name}</td>
									<td><button class="btn-choose">选择</button></td>
								`;

								// 绑定选择事件
								row.querySelector('.btn-choose').addEventListener('click', function() {
									selectMaterial(material);
									//console.log(material)
								});

								tbody.appendChild(row);
							});
						} else {
							console.error('获取物料数据失败:', data.msg);
						}
					})
					.catch(error => {
						console.error('获取物料数据出错:', error);
					});
				}

				// 选择物料
				function selectMaterial(material) {
					if (!window.currentSelectingRow?.element) {
						console.error('没有选中的行或元素不存在');
						return;
					}
					const row = window.currentSelectingRow.element;
					const inputs = {
						code: row.querySelector(".material-code"),
						name: row.querySelector(".material-name"),
						spec: row.querySelector(".specification"),
						unit: row.querySelector(".unit"),

						// 新增获取采购订单号、仓库、入库单号输入框元素
						orderNumber: row.querySelector(".order-number"),
						warehouse: row.querySelector(".warehouse"),
						receiptNumber: row.querySelector(".receipt-number")
					};
					console.log("当前行和输入元素:", {row, inputs});

					if (inputs.code && inputs.name && inputs.spec && inputs.unit) {
						inputs.code.value = material.material_code || '';
						inputs.name.value = material.material_name || '';
						inputs.spec.value = material.model_specification || '';
						inputs.unit.value = material.unit_of_measurement_name || '';
						// 为采购订单号、仓库、入库单号设置默认值
						if (inputs.orderNumber) inputs.orderNumber.value = '手工单据';
						if (inputs.warehouse) inputs.warehouse.value = '手工单据';
						if (inputs.receiptNumber) inputs.receiptNumber.value = '手工单据';


						// 触发输入事件
						Object.values(inputs).forEach(input => input.dispatchEvent(new Event('input')));
					}else {
						console.error('部分输入元素未找到');
					}
					if (modal) modal.style.display = 'none';
				}

				// 更新行号
				function updateRowNumbers() {
					const rows = document.querySelectorAll('#material-tbody tr');
					rows.forEach((row, index) => {
						row.cells[0].textContent = index + 1;
						row.dataset.index = index + 1;
					});
					rowCount = rows.length;
				}
		})


	</script>

</body>
</html>